package com.lock.condition;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName:com.lock.condition
 * @ClassName:Test02
 * @Description: 使用condition实现生产者 消费者 设计模式  两个线程交替打印
 * @Author: zhangxiaoyu
 * @date 2021/1/20 14:50
 */
public class Test02 {

    static class MyService{

        private Lock lock = new ReentrantLock();
        private Condition condition = lock.newCondition();

        private boolean flag = true;  //交替打印标志

        //定义方法打印
        public void  printOne(){
            try {
                lock.lock();
                while (flag){
                    
                    System.out.println(Thread.currentThread().getName()+"wait -------");
                    condition.await();
                }
                //为false 打印
                System.out.println(Thread.currentThread().getName()+"--------------------");

                flag = true;
                condition.signal();  //通知另外的线程打印
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }


        //定义方法打印
        public void  printTow(){
            try {
                lock.lock();
                while (!flag){
                    condition.await();
                }
                //为true 打印
                System.out.println(Thread.currentThread().getName()+"**********************");

                flag = false;
                condition.signal();  //通知另外的线程打印
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }


    public static void main(String[] args){
         MyService t = new MyService();

         new Thread(new Runnable() {
             @Override
             public void run() {
                 for (int i =0;i<100;i++){
                     t.printOne();
                 }
             }
         }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i =0;i<100;i++){
                    t.printTow();
                }
            }
        }).start();
    }

}
